package com.example.oauth2.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据库相关配置
 */
@Configuration
@EnableJpaRepositories(basePackages = "com.example.oauth2.repository",
        entityManagerFactoryRef = "oauthEntityManagerFactory", transactionManagerRef = "oauthTransactionFactory")

public class DataBaseConfig {

    @Bean
    @Primary
    @ConfigurationProperties("mysql.oauth.datasource")
    public DataSourceProperties oauthDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Primary
    @ConfigurationProperties("mysql.oauth.datasource.configuration")
    public DataSource oauthDataSource() {
        return oauthDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

    @Primary
    @Bean(name = "oauthEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean oauthEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("hibernate.hbm2ddl.auto", "update");
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
        properties.put("hibernate.show_sql", "false");
        return builder.dataSource(oauthDataSource())
                .properties(properties)
                .packages("com.example.oauth2.entry")
                .persistenceUnit("oauthPersistenceUnit").build();
    }

    @Primary
    @Bean(name = "oauthTransactionFactory")
    public PlatformTransactionManager oauthTransactionManager(
            final @Qualifier("oauthEntityManagerFactory") LocalContainerEntityManagerFactoryBean oauthEntityManagerFactory) {
        return new JpaTransactionManager(oauthEntityManagerFactory.getObject());
    }
}
